﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Drawing;
using System.IO;
using System.Data;
using System.Collections;
using System.Web;

/// 
/// 导出word
/// Author:lizhao
/// 操作WordML(2003)根据标签插入文本、表格、图片
/// 
namespace Xiaov.SmartWeb.Application.ZNPT
{
  public class WordMLHelper
  {
    /// 
    /// 最短路径图片在导出Word文件中的宽度
    /// webconfig中加入节点 
    /// 
    public string WordWidth
    {
      get
      {
        return System.Configuration.ConfigurationSettings.AppSettings["WordWidth"].ToString();
      }
    }

    /// 
    /// 最短路径图片在导出Word文件中的高度
    /// webconfig中加入节点
    /// 
    public string WordHeight
    {
      get
      {
        return System.Configuration.ConfigurationSettings.AppSettings["WordHeight"].ToString();
      }
    }

    private XmlNamespaceManager nsmgr;
    private XmlDocument xdoc;
    private string strFileInfo;

    public void CreateFileDealer(string FilePath)
    {
      StreamReader sr = new StreamReader(FilePath, System.Text.Encoding.UTF8);
      strFileInfo = sr.ReadToEnd();
      sr.Close();
      sr.Dispose();
    }

    public void ReplaceText(Dictionary<string, string> DataPairs)
    {
      foreach (KeyValuePair<string, string> DataPair in DataPairs)
      {
        strFileInfo = strFileInfo.Replace(DataPair.Key, DataPair.Value);
      }
    }

    public void SaveFile(string FilePath)
    {
      StreamWriter sw = new StreamWriter(FilePath);
      sw.Write(strFileInfo);
      sw.Flush();
      sw.Close();
    }

    public void ReplaceGrid(Dictionary<string, System.Data.DataTable> TablePairs)
    {
      StringBuilder sb = new StringBuilder();
      sb.Append(@"<w:tblPr>");
      sb.Append(@"<w:tblW w:w='0' w:type='auto'/>");
      sb.Append(@"<w:jc w:val='center'/>");
      sb.Append(@"<w:tblBorders>");
      sb.Append(@"<w:top w:val='single' w:sz='4' wx:bdrwidth='10' w:space='0' w:color='auto'/>");//上边线
      sb.Append(@"<w:bottom w:val='single' w:sz='4' wx:bdrwidth='10' w:space='0' w:color='auto'/>");
      sb.Append(@"<w:left w:val='single' w:sz='4' wx:bdrwidth='10' w:space='0' w:color='auto'/>");
      sb.Append(@"<w:right w:val='single' w:sz='4' wx:bdrwidth='10' w:space='0' w:color='auto'/>");
      sb.Append(@"<w:insideH w:val='single' w:sz='4' wx:bdrwidth='10' w:space='0' w:color='auto'/>");
      sb.Append(@"<w:insideV w:val='single' w:sz='4' wx:bdrwidth='10' w:space='0' w:color='auto'/>");
      sb.Append(@"</w:tblBorders>");
      sb.Append(@"</w:tblPr>");

      string strGridAttr = sb.ToString();

      sb.Clear();
      sb.Append(@"");

      foreach (KeyValuePair<string, System.Data.DataTable> TablePair in TablePairs)
      {
        // strFileInfo = strFileInfo.Replace(TablePair.Key,)
      }

    }


    public void CreateXmlDom(string xmlPath)
    {
      xdoc = new XmlDocument();

      xdoc.Load(xmlPath);
      nsmgr = new XmlNamespaceManager(xdoc.NameTable);
      nsmgr.AddNamespace("w", "http://schemas.microsoft.com/office/word/2003/wordml");
      nsmgr.AddNamespace("v", "urn:schemas-microsoft-com:vml");
      nsmgr.AddNamespace("aml", "http://schemas.microsoft.com/aml/2001/core");
      nsmgr.AddNamespace("wx", "http://schemas.microsoft.com/office/word/2003/auxHint");
    }

    //  string serverPath = HttpContext.Current.Server.MapPath("~");//Replace("../", "\\").Replace("/", "\\")
    public void GenNewWordXML(string strFilePath, Dictionary<string, string> DataPairs, string name)
    {
      StringBuilder sb = new StringBuilder();
      XmlNodeList nodeList = xdoc.SelectNodes("//w:t", nsmgr);
      ArrayList tagList = new ArrayList();
      foreach (XmlNode node in nodeList)
      {
        string strInnerText = node.InnerText;
        sb.Append(strInnerText);
      }
      string strInfo = sb.ToString();
      //      string strTagInfo = "";
      InnertextToTagList(strInfo, tagList);
      ArrayList ValueList = new ArrayList();

      for (int i = 0; i < tagList.Count; i++)
      {
        if (DataPairs.ContainsKey(tagList[i].ToString()))
        {
          ValueList.Add(DataPairs[tagList[i].ToString()].ToString());
        }
        else
        {
          ValueList.Add("");
        }
      }

      string fileData = string.Empty;
      try
      {   ///读取文件的内容       
        StreamReader reader = new StreamReader(strFilePath, System.Text.Encoding.UTF8);
        fileData = reader.ReadToEnd();
        reader.Close();
      }
      catch (Exception ex)
      {
        throw new Exception(ex.Message, ex);
      }

      StringBuilder sbFileInfo = new StringBuilder();
      int nCount = 0;
      int nPos = 0;
      do
      {
        int BeginPos = fileData.IndexOf("$", nPos);
        if (BeginPos == -1)
        {
          sbFileInfo.Append(fileData.Substring(nPos, fileData.Length - nPos));
          break;
        }

        sbFileInfo.Append(fileData.Substring(nPos, BeginPos - nPos));

        string strTemp = sbFileInfo.ToString();

        int EndPos = fileData.IndexOf("$", BeginPos + 1);
        if (EndPos == -1)
        {
          break;
        }

        sbFileInfo.Append(ValueList[nCount]);

        strTemp = sbFileInfo.ToString();

        nCount++;
        nPos = EndPos + 1;
      } while (nPos > 0 && nPos <= fileData.Length);

      string filePath = HttpContext.Current.Server.MapPath("~");
      Guid guid = Guid.NewGuid();
      string strDealedInfo = sbFileInfo.ToString();
      FileStream fs = new FileStream(filePath + "ZNPT/report/" + name + ".doc", FileMode.Create, FileAccess.Write);
      StreamWriter rw = new StreamWriter(fs, System.Text.Encoding.UTF8);
      rw.Write(strDealedInfo);
      rw.Flush();
      rw.Close();
      fs.Close();
      FileDownload(filePath + "ZNPT/report/" + name + ".doc");
    }

    private void FileDownload(string FullFileName)
    {
      Guid guid = Guid.NewGuid();
      FileInfo DownloadFile = new FileInfo(FullFileName);
      HttpContext.Current.Response.Clear();
      HttpContext.Current.Response.ClearHeaders();
      HttpContext.Current.Response.Buffer = false;
      HttpContext.Current.Response.ContentType = "application/octet-stream";
      HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + FullFileName);
      HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
      HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
      HttpContext.Current.Response.Flush();
      HttpContext.Current.Response.End();
    }


    static int InnertextToTagList(string WithinString, ArrayList TagList)
    {
      int nCount = 0;
      int nPos = 0;
      do
      {
        int BeginPos = WithinString.IndexOf("$", nPos);
        if (BeginPos == -1)
        {
          break;
        }
        int EndPos = WithinString.IndexOf("$", BeginPos + 1);
        if (EndPos == -1)
        {
          break;
        }
        TagList.Add(WithinString.Substring(BeginPos, EndPos - BeginPos + 1));
        nCount++;
        nPos = EndPos + 1;
      } while (nPos > 0 && nPos <= WithinString.Length);

      return nCount;
    }
    static int GetTagList(string WithinString, string search, ArrayList TagList)
    {
      if (string.IsNullOrEmpty(search))
        throw new ArgumentNullException("search");
      int counter = 0;
      int index = WithinString.IndexOf(search, 0);
      int lastIndex = 0;
      while (index >= 0 && index < WithinString.Length)
      {
        counter++;
        lastIndex = index;
        index = WithinString.IndexOf(search, index + search.Length);
        if (counter > 0 && counter % 2 != 0)
        {
          TagList.Add(WithinString.Substring(lastIndex, index - lastIndex + 1));
        }
      }
      return counter;
    }
    #region 导出Word文档的方法

    /// 
    /// 设置节点的值
    /// 
    /// 

    public void SetNodeText(Dictionary<string, string> bookmarks)
    {
      XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
      foreach (XmlNode node in nodeList)
      {
        SetBookMarkTexts(xdoc, node, bookmarks);
      }
    }

    /// 
    /// 根据数据集插入数据,数据集中的数据表含有一条数据
    /// 
    /// 
    public void SetNodeTextDataSet(DataSet ds)
    {
      Dictionary<string, string> bookmarkValues = new Dictionary<string, string>();
      foreach (System.Data.DataTable dt in ds.Tables)
      {
        foreach (DataColumn dc in dt.Columns)
        {
          if (dt.Rows.Count > 0)
          {
            bookmarkValues.Add(dt.TableName + "_" + dc.ColumnName, dt.Rows[0][dc.ColumnName].ToString());
          }
        }
      }
      SetNodeText(bookmarkValues);
    }

    /// 
    /// 根据数据表插入数据,数据表含有一条数据
    /// 
    /// 
    public void SetNodeTextDataTable(System.Data.DataTable dt)
    {
      Dictionary<string, string> bookmarkValues = new Dictionary<string, string>();

      foreach (DataColumn dc in dt.Columns)
      {
        if (dt.Rows.Count > 0)
        {
          bookmarkValues.Add(dt.TableName + "_" + dc.ColumnName, dt.Rows[0][dc.ColumnName].ToString());
        }
      }
      SetNodeText(bookmarkValues);
    }

    /// 
    /// 插入一张表数据,表中含有多条数据
    /// 
    /// 
    public void SetNodeTable(Dictionary<string, System.Data.DataTable> tables)
    {
      Dictionary<string, WordTable> wordtables = new Dictionary<string, WordTable>();

      foreach (KeyValuePair<string, System.Data.DataTable> table in tables)
      {
        wordtables.Add(table.Key, WordTable.GetWordTabelFromDataTable(table.Value));
      }
      XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
      foreach (XmlNode node in nodeList)
      {
        SetBookMarkTablesHorizontal(xdoc, node, wordtables);
      }
    }

    /// 
    /// 插入一张表数据,表中含有多条数据
    /// 
    /// 
    public void SetNodeTable(Dictionary<string, WordTable> wordtables)
    {
      XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
      foreach (XmlNode node in nodeList)
      {
        SetBookMarkTablesHorizontal(xdoc, node, wordtables);
      }
    }

    /// 
    /// 插入一张表数据,表中含有多条数据
    /// 
    /// 
    /// 是否为水平列表,即列名在数据上方
    public void SetNodeTable(Dictionary<string, System.Data.DataTable> tables, bool IsHorizontal)
    {
      Dictionary<string, WordTable> wordtables = new Dictionary<string, WordTable>();

      foreach (KeyValuePair<string, System.Data.DataTable> table in tables)
      {
        wordtables.Add(table.Key, WordTable.GetWordTabelFromDataTable(table.Value));
      }
      XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
      foreach (XmlNode node in nodeList)
      {
        if (IsHorizontal)
          SetBookMarkTablesHorizontal(xdoc, node, wordtables);
        else
          SetBookMarkTablesVertical(xdoc, node, wordtables);
      }
    }

    /// 
    /// 插入一张表数据,表中含有多条数据
    /// 
    /// 
    /// 是否为水平列表,即列名在数据上方
    public void SetNodeTable(Dictionary<string, WordTable> wordtables, bool IsHorizontal)
    {
      XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
      foreach (XmlNode node in nodeList)
      {
        if (IsHorizontal)
          SetBookMarkTablesHorizontal(xdoc, node, wordtables);
        else
          SetBookMarkTablesVertical(xdoc, node, wordtables);
      }
    }

    /// 
    /// 插入一张表数据,表中含有多条数据
    /// 图片的列是传入datatabele的最后一列,且最后一列为图片的绝对地址
    /// 
    /// 
    /// 是否为水平列表,即列名在数据上方
    /// 是否含有图片
    public void SetNodeTable(Dictionary<string, System.Data.DataTable> tables, bool IsHorizontal, bool ExistPicture)
    {
      Dictionary<string, WordTable> wordtables = new Dictionary<string, WordTable>();

      foreach (KeyValuePair<string, System.Data.DataTable> table in tables)
      {
        wordtables.Add(table.Key, WordTable.GetWordTabelFromDataTable(table.Value));
      }
      XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
      foreach (XmlNode node in nodeList)
      {
        if (ExistPicture)
        {
          if (IsHorizontal)
            SetBookMarkTablesPictureHorizontal(xdoc, node, wordtables);
          else
            SetBookMarkTablesPictureVertical(xdoc, node, wordtables);
        }
        else
        {
          if (IsHorizontal)
            SetBookMarkTablesHorizontal(xdoc, node, wordtables);
          else
            SetBookMarkTablesVertical(xdoc, node, wordtables);
        }
      }
    }

    /// 
    /// 插入一张表数据,表中含有多条数据
    /// 图片的列是传入wordtables的最后一列,且最后一列为图片的绝对地址
    /// 
    /// 
    /// 是否为水平列表,即列名在数据上方
    /// 是否含有图片
    public void SetNodeTable(Dictionary<string, WordTable> wordtables, bool IsHorizontal, bool ExistPicture)
    {
      XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
      foreach (XmlNode node in nodeList)
      {
        if (ExistPicture)
        {
          if (IsHorizontal)
            SetBookMarkTablesPictureHorizontal(xdoc, node, wordtables);
          else
            SetBookMarkTablesPictureVertical(xdoc, node, wordtables);
        }
        else
        {
          if (IsHorizontal)
            SetBookMarkTablesHorizontal(xdoc, node, wordtables);
          else
            SetBookMarkTablesVertical(xdoc, node, wordtables);
        }
      }
    }

    /// 
    /// 设置插入的图品数据
    /// 
    /// 
    public void SetNodePic(Dictionary<string, WordPic> picpaths)
    {
      XmlNodeList nodeList = xdoc.SelectNodes("//aml:annotation[@w:type='Word.Bookmark.Start']", nsmgr);
      //XmlNodeList nodeList = xdoc.SelectNodes("//w:bookmarkStart", nsmgr);
      foreach (XmlNode node in nodeList)
      {
        SetBookMarkPics(xdoc, node, picpaths);
      }
    }

    /// 
    /// 保存导出的数据
    /// 
    /// 
    public void Save(string docPath)
    {
      xdoc.Save(docPath);
    }

    #endregion

    #region 导出word文档内部方法

    /// 
    /// 根据标签插入对应的值
    /// 
    /// 
    /// 
    /// 
    private void SetBookMarkTexts(XmlDocument xdoc, XmlNode node, Dictionary<string, string> bookmarks)
    {
      //找到bookmark结束标记
      if (node.NextSibling.Name.ToString() == "aml:annotation")
      {
        //查找bookmarks中是否在word标签
        if (bookmarks.ContainsKey(node.Attributes["w:name"].Value))
        {
          //得到node上一个兄弟节点style ("w:rPr")的克隆，以备添给新加内容，样式继承
          XmlNode nodeStyle = null;
          if (node.PreviousSibling != null)
            nodeStyle = node.PreviousSibling.CloneNode(true);
          else
            nodeStyle = node.ParentNode.SelectNodes("//w:r", nsmgr)[0].CloneNode(true);
          //父节点 "w:p"
          XmlNode bookmrkParent = node.ParentNode;
          XmlElement tagRun;
          tagRun = xdoc.CreateElement("w:r", nsmgr.LookupNamespace("w"));
          bookmrkParent.AppendChild(tagRun);
          //添加样式
          if (nodeStyle.SelectSingleNode("//w:rPr", nsmgr) != null)
            tagRun.AppendChild(nodeStyle.SelectSingleNode("//w:rPr", nsmgr));
          XmlElement tagText;
          tagText = xdoc.CreateElement("w:t", nsmgr.LookupNamespace("w"));
          tagRun.AppendChild(tagText);
          //插入(w:t)文本作为内容，追加至文本节点

          if (bookmarks[node.Attributes["w:name"].Value] == null)
            return;
          XmlNode nodeText;
          nodeText = xdoc.CreateNode(XmlNodeType.Text, "w:t", nsmgr.LookupNamespace("w"));
          nodeText.Value = bookmarks[node.Attributes["w:name"].Value].ToString();
          tagText.AppendChild(nodeText);
        }
      }
    }

    /// 
    /// 根据标签水平插入一张表数据，即列名在数据上侧
    /// 
    /// 
    /// 
    /// 
    private void SetBookMarkTablesHorizontal(XmlDocument xdoc, XmlNode node, Dictionary<string, WordTable> wordtables)
    {
      if (node.NextSibling.Name.ToString() == "aml:annotation")
      {
        //查找bookmarks中是否在word标签
        if (wordtables.ContainsKey(node.Attributes["w:name"].Value))
        {
          // "w:p"节点的父节点
          XmlNode bookmrkParent = node.ParentNode;
          XmlNode bookmrkParentParent = node.ParentNode.ParentNode;
          XmlElement tagtable;
          tagtable = xdoc.CreateElement("w:tbl", nsmgr.LookupNamespace("w"));
          bookmrkParentParent.InsertAfter(tagtable, bookmrkParent);

          SetImportTableBorder(ref xdoc, ref tagtable);

          XmlElement tagtr;
          tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
          tagtable.AppendChild(tagtr);

          foreach (string headstr in wordtables[node.Attributes["w:name"].Value].TableHeads)
          {
            SetTableTitle(ref tagtr, headstr);
          }

          for (int i = 0; i < wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(0); i++)
          {
            tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
            tagtable.AppendChild(tagtr);

            for (int j = 0; j < wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(1); j++)
            {
              string content = wordtables[node.Attributes["w:name"].Value].TableValues[i, j];
              SetTableContent(ref tagtr, content);

            }
          }
        }
      }
    }

    /// 
    /// 根据标签垂直插入一张表数据，即列名在数据左侧
    /// 
    /// 
    /// 
    /// 
    private void SetBookMarkTablesVertical(XmlDocument xdoc, XmlNode node, Dictionary<string, WordTable> wordtables)
    {
      if (node.NextSibling.Name.ToString() == "aml:annotation")
      {
        //查找bookmarks中是否在word标签
        if (wordtables.ContainsKey(node.Attributes["w:name"].Value))
        {
          // "w:p"节点的父节点
          XmlNode bookmrkParent = node.ParentNode;
          XmlNode bookmrkParentParent = node.ParentNode.ParentNode;
          XmlElement tagtable;
          tagtable = xdoc.CreateElement("w:tbl", nsmgr.LookupNamespace("w"));
          bookmrkParentParent.InsertAfter(tagtable, bookmrkParent);

          //设置表格样式
          SetImportTableBorder(ref xdoc, ref tagtable);

          for (int i = 0; i < wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(0); i++)
          {
            for (int j = 0; j < wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(1); j++)
            {
              XmlElement tagtr;
              tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
              tagtable.AppendChild(tagtr);
              if (wordtables[node.Attributes["w:name"].Value].TableHeads[j] == null)
                return;
              string headstr = wordtables[node.Attributes["w:name"].Value].TableHeads[j];
              SetTableTitle(ref tagtr, headstr);
              if (wordtables[node.Attributes["w:name"].Value].TableValues[i, j] == null)
                return;
              string content = wordtables[node.Attributes["w:name"].Value].TableValues[i, j];
              SetTableContent(ref tagtr, content);

            }

          }
        }
      }
    }

    /// 
    /// 根据标签水平插入一张表数据，即列名在数据上侧
    /// 表中最后一列为图片的地址
    /// 
    /// 
    /// 
    /// 
    private void SetBookMarkTablesPictureHorizontal(XmlDocument xdoc, XmlNode node, Dictionary<string, WordTable> wordtables)
    {
      if (node.NextSibling.Name.ToString() == "aml:annotation")
      {
        //查找bookmarks中是否在word标签
        if (wordtables.ContainsKey(node.Attributes["w:name"].Value))
        {
          // "w:p"节点的父节点
          XmlNode bookmrkParent = node.ParentNode;
          XmlNode bookmrkParentParent = node.ParentNode.ParentNode;
          XmlElement tagtable;
          tagtable = xdoc.CreateElement("w:tbl", nsmgr.LookupNamespace("w"));
          bookmrkParentParent.InsertAfter(tagtable, bookmrkParent);

          SetImportTableBorder(ref xdoc, ref tagtable);

          XmlElement tagtr;
          tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
          tagtable.AppendChild(tagtr);

          //循环输入列名，最后一行跳过，最后一行为图片的地址
          for (int i = 0; i < wordtables[node.Attributes["w:name"].Value].TableHeads.Length - 1; i++)
          {
            string headstr = wordtables[node.Attributes["w:name"].Value].TableHeads[i];
            SetTableTitle(ref tagtr, headstr);
          }


          for (int i = 0; i < wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(0); i++)
          {
            tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
            tagtable.AppendChild(tagtr);

            int colLength = wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(1);

            for (int j = 0; j < colLength - 1; j++)
            {
              string content = wordtables[node.Attributes["w:name"].Value].TableValues[i, j];
              SetTableContent(ref tagtr, content);
            }
            tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
            tagtable.AppendChild(tagtr);
            //SetTablePicture(ref tagtr, wordtables[node.Attributes["w:name"].Value].TableValues[i, colLength - 1], (colLength - 1).ToString());
          }
        }
      }
    }

    /// 
    /// 根据标签垂直插入一张表数据，即列名在数据左侧
    /// 表中最后一列为图片的地址
    /// 
    /// 
    /// 
    /// 
    private void SetBookMarkTablesPictureVertical(XmlDocument xdoc, XmlNode node, Dictionary<string, WordTable> wordtables)
    {
      if (node.NextSibling.Name.ToString() == "aml:annotation")
      {
        //查找bookmarks中是否在word标签
        if (wordtables.ContainsKey(node.Attributes["w:name"].Value))
        {
          // "w:p"节点的父节点
          XmlNode bookmrkParent = node.ParentNode;
          XmlNode bookmrkParentParent = node.ParentNode.ParentNode;
          XmlElement tagtable;
          tagtable = xdoc.CreateElement("w:tbl", nsmgr.LookupNamespace("w"));
          bookmrkParentParent.InsertAfter(tagtable, bookmrkParent);

          //设置表格样式
          SetImportTableBorder(ref xdoc, ref tagtable);

          for (int i = 0; i < wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(0); i++)
          {
            int colLength = wordtables[node.Attributes["w:name"].Value].TableValues.GetLength(1);
            XmlElement tagtr;
            for (int j = 0; j < colLength - 1; j++)
            {

              tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
              tagtable.AppendChild(tagtr);
              string headstr = wordtables[node.Attributes["w:name"].Value].TableHeads[j];
              SetTableTitle(ref tagtr, headstr);
              string content = wordtables[node.Attributes["w:name"].Value].TableValues[i, j];
              SetTableContent(ref tagtr, content);
            }
            tagtr = xdoc.CreateElement("w:tr", nsmgr.LookupNamespace("w"));
            tagtable.AppendChild(tagtr);
            //      SetTablePicture(ref tagtr, wordtables[node.Attributes["w:name"].Value].TableValues[i, colLength - 1]);
          }
        }
      }
    }

    /// 
    /// 设置列名
    /// 
    private void SetTableTitle(ref XmlElement tagtr, string headstr)
    {
      XmlElement tagtc;
      tagtc = xdoc.CreateElement("w:tc", nsmgr.LookupNamespace("w"));
      tagtr.AppendChild(tagtc);

      XmlElement tagP;
      tagP = xdoc.CreateElement("w:p", nsmgr.LookupNamespace("w"));
      tagtc.AppendChild(tagP);

      XmlElement tagRun;
      tagRun = xdoc.CreateElement("w:r", nsmgr.LookupNamespace("w"));
      tagP.AppendChild(tagRun);

      //加粗
      //设置字体为
      XmlElement tagPr;
      tagPr = xdoc.CreateElement("w:rPr", nsmgr.LookupNamespace("w"));
      tagRun.AppendChild(tagPr);

      XmlElement tagB;
      tagB = xdoc.CreateElement("w:b", nsmgr.LookupNamespace("w"));
      tagPr.AppendChild(tagB);

      XmlElement tagText;
      tagText = xdoc.CreateElement("w:t", nsmgr.LookupNamespace("w"));
      tagRun.AppendChild(tagText);
      //插入(w:t)文本作为内容，追加至文本节点
      XmlNode nodeText;
      nodeText = xdoc.CreateNode(XmlNodeType.Text, "w:t", nsmgr.LookupNamespace("w"));
      nodeText.Value = headstr;
      tagText.AppendChild(nodeText);
    }

    /// 
    /// 设置表的内容
    /// 
    private void SetTableContent(ref XmlElement tagtr, string content)
    {
      XmlElement tagtc;
      tagtc = xdoc.CreateElement("w:tc", nsmgr.LookupNamespace("w"));
      tagtr.AppendChild(tagtc);

      XmlElement tagP;
      tagP = xdoc.CreateElement("w:p", nsmgr.LookupNamespace("w"));
      tagtc.AppendChild(tagP);

      XmlElement tagRun;
      tagRun = xdoc.CreateElement("w:r", nsmgr.LookupNamespace("w"));
      tagP.AppendChild(tagRun);

      XmlElement tagText;
      tagText = xdoc.CreateElement("w:t", nsmgr.LookupNamespace("w"));
      tagRun.AppendChild(tagText);

      //插入(w:t)文本作为内容，追加至文本节点
      XmlNode nodeText;
      nodeText = xdoc.CreateNode(XmlNodeType.Text, "w:t", nsmgr.LookupNamespace("w"));
      nodeText.Value = content;
      tagText.AppendChild(nodeText);
    }

    /// 
    /// 设置表中图片
    /// 
    /// 
    /// 
    /// Path
    //private void SetTablePicture(ref XmlElement tagtr, string path)
    //{
    //    path = serverPath + path.Replace("../", "\\").Replace("/", "\\");

    //    XmlElement tagtc;
    //    tagtc = xdoc.CreateElement("w:tc", nsmgr.LookupNamespace("w"));
    //    tagtr.AppendChild(tagtc);


    //    XmlElement tagP;
    //    tagP = xdoc.CreateElement("w:p", nsmgr.LookupNamespace("w"));
    //    tagtc.AppendChild(tagP);

    //    XmlElement tagRun;
    //    tagRun = xdoc.CreateElement("w:r", nsmgr.LookupNamespace("w"));
    //    tagP.AppendChild(tagRun);

    //    XmlElement tagText;
    //    tagText = xdoc.CreateElement("w:t", nsmgr.LookupNamespace("w"));
    //    tagRun.AppendChild(tagText);
    //    XmlElement tagPic;

    //    if (File.Exists(path))
    //    {
    //        Bitmap bitmap = new Bitmap(path);

    //        tagPic = xdoc.CreateElement("w:pict", nsmgr.LookupNamespace("w"));
    //        tagRun.AppendChild(tagPic);

    //        XmlElement tagbindData;
    //        tagbindData = xdoc.CreateElement("w:binData", nsmgr.LookupNamespace("w"));
    //        tagPic.AppendChild(tagbindData);

    //        XmlAttribute nodeAttr;
    //        nodeAttr = xdoc.CreateAttribute("w:name", nsmgr.LookupNamespace("w"));
    //        nodeAttr.Value = "wordml://" + Path.GetFileName(path);
    //        tagbindData.Attributes.Append(nodeAttr);

    //        //xml:space="preserve"
    //        nodeAttr = xdoc.CreateAttribute("xml:space");
    //        nodeAttr.Value = "preserve";
    //        tagbindData.Attributes.Append(nodeAttr);

    //        XmlNode nodePicValue;
    //        nodePicValue = xdoc.CreateNode(XmlNodeType.Text, "w:binData", nsmgr.LookupNamespace("w"));
    //        nodePicValue.Value = ImgToBase64String(path);
    //        tagbindData.AppendChild(nodePicValue);

    //        XmlElement tagShape;
    //        tagShape = xdoc.CreateElement("v:shape", nsmgr.LookupNamespace("v"));
    //        tagPic.AppendChild(tagShape);

    //        XmlAttribute tagStyle;
    //        tagStyle = xdoc.CreateAttribute("style");
    //        tagStyle.Value = "width:" + WordWidth + "pt;height:" + WordHeight + "pt;";
    //        tagShape.Attributes.Append(tagStyle);


    //        XmlElement tagimagedata;
    //        tagimagedata = xdoc.CreateElement("v:imagedata", nsmgr.LookupNamespace("v"));
    //        tagShape.AppendChild(tagimagedata);

    //        nodeAttr = xdoc.CreateAttribute("src");
    //        nodeAttr.Value = "wordml://" + Path.GetFileName(path);
    //        tagimagedata.Attributes.Append(nodeAttr);
    //    }

    //}

    /// 
    /// 设置表中图片
    /// 
    /// 
    /// 
    /// Path
    /// 合并的列数
    //private void SetTablePicture(ref XmlElement tagtr, string path, string colNum)
    //{
    //    path = serverPath + path.Replace("../", "\\").Replace("/", "\\");


    //    XmlElement tagtc;
    //    tagtc = xdoc.CreateElement("w:tc", nsmgr.LookupNamespace("w"));
    //    tagtr.AppendChild(tagtc);

    //    if (colNum != string.Empty)
    //    {
    //        XmlElement tagtcPr;
    //        tagtcPr = xdoc.CreateElement("w:tcPr", nsmgr.LookupNamespace("w"));
    //        tagtc.AppendChild(tagtcPr);

    //        XmlElement tagtcW;
    //        tagtcW = xdoc.CreateElement("w:tcW", nsmgr.LookupNamespace("w"));
    //        tagtcPr.AppendChild(tagtcW);

    //        XmlAttribute nodew;
    //        nodew = xdoc.CreateAttribute("w:w", nsmgr.LookupNamespace("w"));
    //        nodew.Value = "0";
    //        tagtcW.Attributes.Append(nodew);

    //        XmlAttribute nodetype;
    //        nodetype = xdoc.CreateAttribute("w:type", nsmgr.LookupNamespace("w"));
    //        nodetype.Value = "auto";
    //        tagtcW.Attributes.Append(nodetype);

    //        XmlElement taggridSpan;
    //        taggridSpan = xdoc.CreateElement("w:gridSpan", nsmgr.LookupNamespace("w"));
    //        tagtcPr.AppendChild(taggridSpan);

    //        XmlAttribute nodegridSpan;
    //        nodegridSpan = xdoc.CreateAttribute("w:val", nsmgr.LookupNamespace("w"));
    //        nodegridSpan.Value = colNum;
    //        taggridSpan.Attributes.Append(nodegridSpan);
    //    }

    //    XmlElement tagP;
    //    tagP = xdoc.CreateElement("w:p", nsmgr.LookupNamespace("w"));
    //    tagtc.AppendChild(tagP);

    //    XmlElement tagRun;
    //    tagRun = xdoc.CreateElement("w:r", nsmgr.LookupNamespace("w"));
    //    tagP.AppendChild(tagRun);

    //    XmlElement tagText;
    //    tagText = xdoc.CreateElement("w:t", nsmgr.LookupNamespace("w"));
    //    tagRun.AppendChild(tagText);
    //    if (File.Exists(path))
    //    {
    //        Bitmap bitmap = new Bitmap(path);
    //        XmlElement tagPic;
    //        tagPic = xdoc.CreateElement("w:pict", nsmgr.LookupNamespace("w"));
    //        tagRun.AppendChild(tagPic);

    //        XmlElement tagbindData;
    //        tagbindData = xdoc.CreateElement("w:binData", nsmgr.LookupNamespace("w"));
    //        tagPic.AppendChild(tagbindData);

    //        XmlAttribute nodeAttr;
    //        nodeAttr = xdoc.CreateAttribute("w:name", nsmgr.LookupNamespace("w"));
    //        nodeAttr.Value = "wordml://" + Path.GetFileName(path);
    //        tagbindData.Attributes.Append(nodeAttr);

    //        //xml:space="preserve"
    //        nodeAttr = xdoc.CreateAttribute("xml:space");
    //        nodeAttr.Value = "preserve";
    //        tagbindData.Attributes.Append(nodeAttr);

    //        XmlNode nodePicValue;
    //        nodePicValue = xdoc.CreateNode(XmlNodeType.Text, "w:binData", nsmgr.LookupNamespace("w"));
    //        nodePicValue.Value = ImgToBase64String(path);
    //        tagbindData.AppendChild(nodePicValue);

    //        XmlElement tagShape;
    //        tagShape = xdoc.CreateElement("v:shape", nsmgr.LookupNamespace("v"));
    //        tagPic.AppendChild(tagShape);

    //        XmlAttribute tagStyle;
    //        tagStyle = xdoc.CreateAttribute("style");
    //        tagStyle.Value = "width:" + WordWidth + "pt;height:" + WordHeight + "pt;";
    //        tagShape.Attributes.Append(tagStyle);


    //        XmlElement tagimagedata;
    //        tagimagedata = xdoc.CreateElement("v:imagedata", nsmgr.LookupNamespace("v"));
    //        tagShape.AppendChild(tagimagedata);

    //        nodeAttr = xdoc.CreateAttribute("src");
    //        nodeAttr.Value = "wordml://" + Path.GetFileName(path);
    //        tagimagedata.Attributes.Append(nodeAttr);
    //    }

    //}

    /// 
    /// 设置导出表的边框样式
    /// 
    /// 
    private void SetImportTableBorder(ref XmlDocument xdoc, ref XmlElement tagtable)
    {

      XmlElement tagborder;
      tagborder = xdoc.CreateElement("w:tblBorders", nsmgr.LookupNamespace("w"));
      tagtable.AppendChild(tagborder);

      XmlElement tagtop;
      tagtop = xdoc.CreateElement("w:top", nsmgr.LookupNamespace("w"));
      tagborder.AppendChild(tagtop);

      XmlAttribute borderValAtrr;
      borderValAtrr = xdoc.CreateAttribute("w:val", nsmgr.LookupNamespace("w"));
      borderValAtrr.Value = "single";
      tagtop.Attributes.Append(borderValAtrr);

      XmlAttribute borderSzAtrr;
      borderSzAtrr = xdoc.CreateAttribute("w:sz", nsmgr.LookupNamespace("w"));
      borderSzAtrr.Value = "4";
      tagtop.Attributes.Append(borderSzAtrr);

      XmlAttribute borderwidthAtrr;
      borderwidthAtrr = xdoc.CreateAttribute("wx:bdrwidth", nsmgr.LookupNamespace("wx"));
      borderwidthAtrr.Value = "10";
      tagtop.Attributes.Append(borderwidthAtrr);

      XmlAttribute borderspaceAtrr;
      borderspaceAtrr = xdoc.CreateAttribute("w:space", nsmgr.LookupNamespace("w"));
      borderspaceAtrr.Value = "0";
      tagtop.Attributes.Append(borderspaceAtrr);

      XmlAttribute bordercolorAtrr;
      bordercolorAtrr = xdoc.CreateAttribute("w:color", nsmgr.LookupNamespace("w"));
      bordercolorAtrr.Value = "auto";
      tagtop.Attributes.Append(bordercolorAtrr);

      XmlElement tagleft;
      tagleft = xdoc.CreateElement("w:left", nsmgr.LookupNamespace("w"));
      tagborder.AppendChild(tagleft);
      tagleft.Attributes.Append(borderValAtrr.Clone() as XmlAttribute);
      tagleft.Attributes.Append(borderSzAtrr.Clone() as XmlAttribute);
      tagleft.Attributes.Append(borderwidthAtrr.Clone() as XmlAttribute);
      tagleft.Attributes.Append(borderspaceAtrr.Clone() as XmlAttribute);
      tagleft.Attributes.Append(bordercolorAtrr.Clone() as XmlAttribute);

      XmlElement tagbottom;
      tagbottom = xdoc.CreateElement("w:bottom", nsmgr.LookupNamespace("w"));
      tagborder.AppendChild(tagbottom);
      tagbottom.Attributes.Append(borderValAtrr.Clone() as XmlAttribute);
      tagbottom.Attributes.Append(borderSzAtrr.Clone() as XmlAttribute);
      tagbottom.Attributes.Append(borderwidthAtrr.Clone() as XmlAttribute);
      tagbottom.Attributes.Append(borderspaceAtrr.Clone() as XmlAttribute);
      tagbottom.Attributes.Append(bordercolorAtrr.Clone() as XmlAttribute);

      XmlElement tagright;
      tagright = xdoc.CreateElement("w:right", nsmgr.LookupNamespace("w"));
      tagborder.AppendChild(tagright);
      tagright.Attributes.Append(borderValAtrr.Clone() as XmlAttribute);
      tagright.Attributes.Append(borderSzAtrr.Clone() as XmlAttribute);
      tagright.Attributes.Append(borderwidthAtrr.Clone() as XmlAttribute);
      tagright.Attributes.Append(borderspaceAtrr.Clone() as XmlAttribute);
      tagright.Attributes.Append(bordercolorAtrr.Clone() as XmlAttribute);

      XmlElement taginsideH;
      taginsideH = xdoc.CreateElement("w:insideH", nsmgr.LookupNamespace("w"));
      tagborder.AppendChild(taginsideH);
      taginsideH.Attributes.Append(borderValAtrr.Clone() as XmlAttribute);
      taginsideH.Attributes.Append(borderSzAtrr.Clone() as XmlAttribute);
      taginsideH.Attributes.Append(borderwidthAtrr.Clone() as XmlAttribute);
      taginsideH.Attributes.Append(borderspaceAtrr.Clone() as XmlAttribute);
      taginsideH.Attributes.Append(bordercolorAtrr.Clone() as XmlAttribute);

      XmlElement taginsideV;
      taginsideV = xdoc.CreateElement("w:insideV", nsmgr.LookupNamespace("w"));
      tagborder.AppendChild(taginsideV);
      taginsideV.Attributes.Append(borderValAtrr.Clone() as XmlAttribute);
      taginsideV.Attributes.Append(borderSzAtrr.Clone() as XmlAttribute);
      taginsideV.Attributes.Append(borderwidthAtrr.Clone() as XmlAttribute);
      taginsideV.Attributes.Append(borderspaceAtrr.Clone() as XmlAttribute);
      taginsideV.Attributes.Append(bordercolorAtrr.Clone() as XmlAttribute);

    }

    /// 
    /// 根据标签插入一张图片
    /// 
    /// 
    /// 
    /// 
    private void SetBookMarkPics(XmlDocument xdoc, XmlNode node, Dictionary<string, WordPic> picpaths)
    {
      if (node.NextSibling.Name.ToString() == "aml:annotation")//w:bookmarkEnd
      {
        //查找bookmarks中是否在word标签
        if (picpaths.ContainsKey(node.Attributes["w:name"].Value))
        {
          // "w:p"节点的父节点
          XmlNode bookmrkParent = node.ParentNode;
          XmlNode bookmrkParentParent = node.ParentNode.ParentNode;

          XmlElement tagPic;
          tagPic = xdoc.CreateElement("w:pict", nsmgr.LookupNamespace("w"));
          bookmrkParentParent.InsertAfter(tagPic, bookmrkParent);

          XmlElement tagbindData;
          tagbindData = xdoc.CreateElement("w:binData", nsmgr.LookupNamespace("w"));
          tagPic.AppendChild(tagbindData);

          XmlAttribute nodeAttr;
          nodeAttr = xdoc.CreateAttribute("w:name", nsmgr.LookupNamespace("w"));
          nodeAttr.Value = "wordml://" + Path.GetFileName(picpaths[node.Attributes["w:name"].Value].PicPath);
          tagbindData.Attributes.Append(nodeAttr);

          //xml:space="preserve"
          nodeAttr = xdoc.CreateAttribute("xml:space");
          nodeAttr.Value = "preserve";
          tagbindData.Attributes.Append(nodeAttr);


          XmlNode nodePicValue;
          nodePicValue = xdoc.CreateNode(XmlNodeType.Text, "w:binData", nsmgr.LookupNamespace("w"));
          nodePicValue.Value = ImgToBase64String(picpaths[node.Attributes["w:name"].Value].PicPath);
          tagbindData.AppendChild(nodePicValue);

          XmlElement tagShape;
          tagShape = xdoc.CreateElement("v:shape", nsmgr.LookupNamespace("v"));
          tagPic.AppendChild(tagShape);


          XmlAttribute tagStyle;
          tagStyle = xdoc.CreateAttribute("style");
          tagStyle.Value = "width:" + picpaths[node.Attributes["w:name"].Value].Width + "pt;height:" + picpaths[node.Attributes["w:name"].Value].Height + "pt;";
          tagShape.Attributes.Append(tagStyle);


          XmlElement tagimagedata;
          tagimagedata = xdoc.CreateElement("v:imagedata", nsmgr.LookupNamespace("v"));
          tagShape.AppendChild(tagimagedata);

          nodeAttr = xdoc.CreateAttribute("src");
          nodeAttr.Value = "wordml://" + Path.GetFileName(picpaths[node.Attributes["w:name"].Value].PicPath);
          tagimagedata.Attributes.Append(nodeAttr);

        }
      }
    }

    private string ImgToBase64String(string Imagefilename)
    {
      System.IO.MemoryStream m = new System.IO.MemoryStream();
      try
      {
        System.Drawing.Bitmap bp = new System.Drawing.Bitmap(Imagefilename);
        bp.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
        byte[] b = m.GetBuffer();
        return Convert.ToBase64String(b);
      }
      finally
      {
        m.Close();
      }
    }

    #endregion

    #region

    //WordTable对象
    public class WordTable
    {

      private string[] _tableHeads;

      public string[] TableHeads
      {
        get { return _tableHeads; }
        set { _tableHeads = value; }
      }

      private string[,] _tableValues;

      public string[,] TableValues
      {
        get { return _tableValues; }
        set { _tableValues = value; }
      }

      public static WordTable GetWordTabelFromDataTable(System.Data.DataTable table)
      {

        WordTable wordtable = new WordTable();
        if (table != null)
        {
          string[] tableheads = new string[table.Columns.Count];
          int i = 0;
          foreach (DataColumn dc in table.Columns)
          {
            tableheads[i] = dc.ColumnName;
            i++;
          }
          wordtable.TableHeads = tableheads;

          i = 0;
          string[,] tablevalues = new string[table.Rows.Count, table.Columns.Count];
          for (int j = 0; j < table.Rows.Count; j++)
          {
            for (int k = 0; k < table.Columns.Count; k++)
            {
              tablevalues[j, k] = table.Rows[j][k].ToString();
            }
          }
          wordtable.TableValues = tablevalues;
        }
        return wordtable;
      }
    }

    //word中插入的图片对象
    public class WordPic
    {
      private int _height;

      public int Height
      {
        get { return _height; }
        set { _height = value; }
      }

      private int _width;

      public int Width
      {
        get { return _width; }
        set { _width = value; }
      }

      private string _picpath;

      public string PicPath
      {
        get { return _picpath; }
        set { _picpath = value; }
      }
    }
  }

}
    #endregion


